<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="downloadExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 员工列表区域 -->
      <el-card style="margin-top: 10px;" :default-sort="{prop: 'mobile'}">
        <el-table :data="employeesList" border>
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" class="staffPhoto"> -->
              <image-holder :src="scope.row.staffPhoto" class="staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" :formatter="formatter" label="聘用形式" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column sortable label="入职时间">
            <template slot-scope="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="correctionTime" label="转正时间" sortable>
            <template slot-scope="scope">
              <span>{{ scope.row.correctionTime | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>

        <!-- 新增员工弹框组件 -->
        <el-dialog title="新增员工" :visible.sync="showDialog" width="50%" @close="closeDialog">
          <emp-dialog
            ref="addEmpt"
            @close="showDialog = false"
            @update-list="updateList"
          />
        </el-dialog>
        <!-- 设置角色弹框组件 -->
        <el-dialog
          title="分配角色"
          :visible.sync="showRoleDialog"
          width="50%"
        >
          <assign-role v-if="showRoleDialog" :role-id="roleId" @close="showRoleDialog=false" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入子组件
import AssignRole from './assignRole'
import EmpDialog from './empDialog'
import { getEmployeeList, delEmployee } from '@/api/employees'
// 引入枚举数据
import EmployeeEnum from '@/constant/employees'
// 导入组件
// import pageTools from '@/components/PageTools'
// 导入时间格式化工具
import dayjs from 'dayjs'
// 懒加载引入
import('@/vendor/Export2Excel').then(excel => {})
export default {
  name: 'Employees',
  components: {
    // pageTools // 导入自定义组件
    EmpDialog,
    AssignRole
  },
  filters: {
    // 过滤器方法的形参是需要格式化的数据
    formatTime(value) {
      // 内部必须有返回值
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false, // 弹窗展示
      showRoleDialog: false, // 分配角色弹框
      roleId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 分配角色弹框事件
    setRole(id) {
      this.showRoleDialog = true
      this.roleId = id
    },
    // 导出 Excel
    async downloadExcel() {
      const res = await getEmployeeList()
      const excelObj = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
      // excel表示导入的模块对象
        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: '员工列表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },

    transData(rows) {
    // 写代码
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const headerKeys = Object.keys(rows[0])
      const header = headerKeys.map(item => {
        return map[item]
      })

      const data = rows.map(obj => {
        return Object.values(obj)
      })

      return { header, data }
    },

    // 监听员工弹窗关闭
    closeDialog() {
      // 获取子组件实例
      this.$refs.addEmpt.resetForm()
    },
    // 刷新列表,隐藏弹窗
    updateList() {
      this.showDialog = false
      // 刷新列表
      this.getEmployeeList()
    },
    // 删除事件
    async delEmp(id) {
      const confirmRes = await this.$confirm('此操作将永久删除人员信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 点击取消
      if (confirmRes === 'cancel') return this.$message('您点击了取消')

      const res = await delEmployee(id)

      // 如果分页只剩一条数据时
      if (this.employeesList.length === 1) {
        // 让页面减一
        this.query.page--
        // 如果第一页只剩一条数据,让page还原为1
        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }
      this.$message.success(res.message)

      // 刷新列表
      this.getEmployeeList()
    },
    // 格式化聘用形式
    formatter(row, column, cellvalue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === Number(cellvalue))
      return obj ? obj.value : '未知'
    },
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.query)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    }
  }

}
</script>

<style lang="scss" scoped>
.staffPhoto{
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
